<template>
  <div class="filter-config">
    <div class="andor" v-if="props.showAndOr && filterList.length > 1">
      <a-select
        v-model="relaValue"
        :options="[
          { label: 'and', value: 'AND' },
          { label: 'or', value: 'OR' }
        ]"
        size="mini"
        :style="{ width: '70px', backgroundColor: '#F6F8FC', border: 'none' }"
        @change="relaChange"
      >
        <template #arrow-icon>
          <IconCaretDown size="12" />
        </template>
      </a-select>
    </div>
    <div class="config">
      <div v-for="(item, index) in filterList" class="config-list">
        <a-select
          v-model="item.dimId"
          :options="dimensionOptions"
          :field-names="{ label: 'columnDimName', value: 'dimensionId' }"
          :style="{ flex: '0 0 120px' }"
          @change="(id: any) => { item.values = []; dimensionChange(id) }"
          placeholder="请选择"
        >
          <template #arrow-icon>
            <IconCaretDown size="12" />
          </template>
        </a-select>
        <a-select
          v-if="showIn"
          v-model="item.opType"
          :options="CONTAIN"
          :style="{ flex: '0 0 90px' }"
          placeholder="请选择"
        >
          <template #arrow-icon>
            <IconCaretDown size="12" />
          </template>
        </a-select>
        <a-select
          v-model="item.values"
          :options="item._dimensionEnumOptions"
          multiple
          placeholder="请选择"
          @change="(values) => dimensionEnumChange(item, values)"
        >
          <template #arrow-icon>
            <IconCaretDown size="12" />
          </template>
        </a-select>
        <a-button
          type="text"
          @click="removeFilterItem(index)"
          style="align-self: stretch"
        >
          <template #icon>
            <IconMinusCircleFill :size="18" style="color: red" />
          </template>
        </a-button>
      </div>
      <a-button
        type="text"
        @click="addFilterItem"
        style="width: auto; margin-top: 5.5px"
      >
        <template #icon>
          <IconPlusCircleFill :size="18" />
        </template>
      </a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, watchEffect } from 'vue';
import {
  IconMinusCircleFill,
  IconPlusCircleFill
} from '@arco-design/web-vue/es/icon';
import { CONTAIN } from '@/constants/indexTree';
import API from '@/services';
import { IconCaretDown } from '@arco-design/web-vue/es/icon';
const props = withDefaults(
  defineProps<{
    modelValue: any;
    metricsId?: number;
    rela?: string;
    showAndOr?: boolean;
    showIn?: boolean;
    dimensionArr?: any[];
  }>(),
  {
    modelValue: null,
    metricsId: undefined,
    rela: 'AND',
    showAndOr: true,
    showIn: true,
    dimensionArr: undefined
  }
);
const emits = defineEmits(['update:rela']);
const relaValue = ref(props.rela);
const filterList = ref<any[]>(props.modelValue || []);
const dimensionOptions = ref<any[]>([]);

watchEffect(() => {
  filterList.value = props.modelValue || [];
});

class CreateFilterItem {
  public dimId: number | undefined;
  public dimName: string;
  public fieldName: string;
  public opType: string;
  public _dimensionEnumOptions: any[];
  public values: number[] | string[];
  public selectLabel: string[];
  constructor(
    dimId = undefined,
    dimName = '',
    fieldName = '',
    opType = '',
    _dimensionEnumOptions = [],
    values = [],
    selectLabel = []
  ) {
    this.dimId = dimId;
    this.dimName = dimName;
    this.fieldName = fieldName;
    this.opType = opType;
    this._dimensionEnumOptions = _dimensionEnumOptions;
    this.values = values;
    this.selectLabel = selectLabel;
  }
}

// 获取过滤维度下拉数据
const getDimensionById = async () => {
  if (props.dimensionArr) {
    dimensionOptions.value = props.dimensionArr;
    return Promise.resolve();
  } else {
    const { code, data = {} } =
      await API.metricsModelRelation.getGetMetricsFilterById({
        id: props.metricsId
      });
    if (code === 200) {
      dimensionOptions.value = (data.queryFieldList || []).filter(
        (item) => item.dimensionId
      );
    }
  }
};

getDimensionById().then(() => {
  let selectedIds = filterList.value.map((item) => {
    if (
      item.dimId &&
      dimensionOptions.value.some((v) => v.dimensionId === item.dimId)
    ) {
      return item.dimId;
    }
  });
  [...new Set(selectedIds)].forEach((id) => {
    id !== void 0 && dimensionChange(id);
  });
});

const relaChange = (val: any) => {
  emits('update:rela', val);
};

// 点击加号
const addFilterItem = () => {
  filterList.value.push(new CreateFilterItem());
};

// 点击减号
const removeFilterItem = (index: number) => {
  filterList.value.splice(index, 1);
};

// 获取维度对应的枚举数据
const dimensionChange = async (id: any) => {
  const { code, data = [] } =
    await API.dataTable.getDataTableGetDimensionEnumById({ id: id });
  filterList.value.forEach((item) => {
    if (item.dimId === id) {
      item.dimName = (
        dimensionOptions.value.find((v) => v.dimensionId === id) || {}
      ).columnDimName;
      item.fieldName = (
        dimensionOptions.value.find((v) => v.dimensionId === id) || {}
      ).columnOtherName;
      if (code === 200) {
        item._dimensionEnumOptions = data;
      }
    }
  });
};

const dimensionEnumChange = (item: any, values: any) => {
  item.selectLabel = values.map((v: any) => {
    return (item._dimensionEnumOptions.find((v1: any) => v1.value === v) || {})
      .label;
  });
};
</script>
<style lang="scss" scoped>
.filter-config {
  display: flex;
  width: 100%;
  .andor {
    border-left: 3px solid #e8ebf2;
    padding: 0 6px;
  }
  .config {
    flex: 1;
    border-left: 3px solid #e8ebf2;
    padding: 0 6px 5.5px 6px;
    .config-list {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;
      & > .arco-select:last-child {
        flex: 1;
      }
    }
  }
}
</style>
<style lang="scss">
.filter-config {
  .config-list {
    & > .arco-select {
      margin-right: 6px;
    }
  }
}
</style>
